package net.maku.tencentsms.service;


import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;

import com.tencentcloudapi.tms.v20201229.TmsClient;
import com.tencentcloudapi.tms.v20201229.models.TextModerationRequest;
import com.tencentcloudapi.tms.v20201229.models.TextModerationResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSONObject;

import java.io.UnsupportedEncodingException;

@Component
public class TencentReportService {
    @Value("${tencent.sms.secretId}")
    private String secretId;

    @Value("${tencent.sms.secretKey}")
    private String secretKey;

    @Value("${tencent.sms.region}")
    private String region;

    @Value("${tencent.sms.BizType}")
    private String BizTypeID;


//    @Value("${tencent.sms.sdkAppId}")
//    private String sdkAppId;
//
//    @Value("${tencent.sms.templateId}")
//    private String templateId;
//
//    @Value("${tencent.sms.signName}")
//    private String signName;

    /**
     * 文本内容审核
     * @param text 待审核的文本内容
     * @return 审核结果JSON对象，包含是否违规、违规类型、置信度等信息（中文显示）
     */
    public JSONObject textReview(String text) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个 HTTP 选项，可选，无特殊需求保持默认即可
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("tms.tencentcloudapi.com");

            // 实例化一个客户端配置选项，可选，无特殊需求保持默认即可
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            // 实例化要请求产品的 client 对象, clientProfile 是可选的
            TmsClient client = new TmsClient(cred, region, clientProfile);

            // 构造文本审核请求对象
            TextModerationRequest req = new TextModerationRequest();
            // 设置待审核的文本内容，将文本转换为Base64编码
            req.setContent(java.util.Base64.getEncoder().encodeToString(text.getBytes("UTF-8")));
            // 如果在控制台配置了自定义审核策略，填写对应的 BizType ，否则可不填
            req.setBizType(BizTypeID);

            // 调用文本审核接口
            TextModerationResponse resp = client.TextModeration(req);

            // 将响应结果转换为JSON对象返回
            String jsonString = TextModerationResponse.toJsonString(resp);
//            System.out.println("原始审核结果: " + jsonString);
            
            // 将原始JSON结果转换为可读的中文格式
            JSONObject originalJson = JSONObject.parseObject(jsonString);
            JSONObject chineseJson = convertToChinese(originalJson);
            System.out.println(chineseJson);
            return originalJson;
        } catch (TencentCloudSDKException e) {
            // 捕获异常并返回错误信息
            JSONObject errorJson = new JSONObject();
            errorJson.put("错误类型", "腾讯云SDK异常");
            errorJson.put("错误代码", e.getErrorCode());
            errorJson.put("错误信息", e.getMessage());
            errorJson.put("请求ID", e.getRequestId());
            System.out.println("审核异常: " + errorJson);
            return errorJson;
        } catch (UnsupportedEncodingException e) {
            // 编码异常处理
            JSONObject errorJson = new JSONObject();
            errorJson.put("错误类型", "编码异常");
            errorJson.put("错误信息", e.getMessage());
            System.out.println("编码异常: " + errorJson);
            return errorJson;
        }
    }
    
    /**
     * 将腾讯云原始结果转换为中文显示
     * @param originalJson 原始返回的JSON结果
     * @return 转换后的中文JSON结果
     */
    public JSONObject convertToChinese(JSONObject originalJson) {
        JSONObject chineseJson = new JSONObject();
        
        // 业务场景ID
        if (originalJson.containsKey("BizType")) {
            chineseJson.put("业务场景ID", originalJson.getString("BizType"));
        }
        
        // 标签类型
        if (originalJson.containsKey("Label")) {
            String label = originalJson.getString("Label");
            String chineseLabel = convertLabelToChinese(label);
            chineseJson.put("检测结果", chineseLabel);
        }
        
        // 处理建议
        if (originalJson.containsKey("Suggestion")) {
            String suggestion = originalJson.getString("Suggestion");
            String chineseSuggestion = convertSuggestionToChinese(suggestion);
            chineseJson.put("处理建议", chineseSuggestion);
        }
        
        // 违规分数
        if (originalJson.containsKey("Score")) {
            chineseJson.put("违规分数", originalJson.getInteger("Score"));
        }
        
        // 子标签
        if (originalJson.containsKey("SubLabel")) {
            String subLabel = originalJson.getString("SubLabel");
            String chineseSubLabel = convertSubLabelToChinese(subLabel);
            chineseJson.put("子类型", chineseSubLabel);
        }
        
        // 请求ID
        if (originalJson.containsKey("RequestId")) {
            chineseJson.put("请求ID", originalJson.getString("RequestId"));
        }
        
        // 详细检测结果
        if (originalJson.containsKey("DetailResults")) {
            chineseJson.put("详细检测结果", convertDetailResults(originalJson.getJSONArray("DetailResults")));
        }
        
        return chineseJson;
    }
    
    /**
     * 标签类型转中文
     */
    private String convertLabelToChinese(String label) {
        switch (label) {
            case "Normal": return "正常";
            case "Porn": return "色情";
            case "Abuse": return "谩骂";
            case "Ad": return "广告";
            case "Illegal": return "违法";
            case "Terror": return "恐怖";
            case "Polity": return "政治相关";
            default: return label;
        }
    }
    
    /**
     * 处理建议转中文
     */
    private String convertSuggestionToChinese(String suggestion) {
        switch (suggestion) {
            case "Block": return "建议拦截";
            case "Review": return "建议人工复审";
            case "Pass": return "建议通过";
            default: return suggestion;
        }
    }
    
    /**
     * 子标签转中文
     */
    private String convertSubLabelToChinese(String subLabel) {
        switch (subLabel) {
            case "SexualBehavior": return "性行为";
            case "SocialMediaPlatform": return "社交平台";
            case "AdTag": return "广告标签";
            case "Politics": return "政治";
            case "Violence": return "暴力";
            default: return subLabel;
        }
    }
    
    /**
     * 详细结果转中文
     */
    private Object convertDetailResults(Object detailResults) {
        if (detailResults == null) {
            return null;
        }
        
        // 遍历所有详细结果，将每个结果中的英文标签转为中文
        com.alibaba.fastjson2.JSONArray originalArray = (com.alibaba.fastjson2.JSONArray) detailResults;
        com.alibaba.fastjson2.JSONArray chineseArray = new com.alibaba.fastjson2.JSONArray();
        
        for (int i = 0; i < originalArray.size(); i++) {
            JSONObject item = originalArray.getJSONObject(i);
            JSONObject chineseItem = new JSONObject();
            
            if (item.containsKey("Label")) {
                String label = item.getString("Label");
                chineseItem.put("检测类型", convertLabelToChinese(label));
            }
            
            if (item.containsKey("Suggestion")) {
                String suggestion = item.getString("Suggestion");
                chineseItem.put("处理建议", convertSuggestionToChinese(suggestion));
            }
            
            if (item.containsKey("Score")) {
                chineseItem.put("分数", item.getInteger("Score"));
            }
            
            if (item.containsKey("Keywords")) {
                chineseItem.put("关键词", item.getJSONArray("Keywords"));
            }
            
            if (item.containsKey("SubLabel")) {
                String subLabel = item.getString("SubLabel");
                if (subLabel != null && !subLabel.isEmpty()) {
                    chineseItem.put("子类型", convertSubLabelToChinese(subLabel));
                }
            }
            
            chineseArray.add(chineseItem);
        }
        
        return chineseArray;
    }
}
